import { saveAs } from "file-saver";
import * as XLSX from "xlsx";
import type {
  StudyExportData,
  ExportConfig,
  ExportResult,
  ExportProgress,
} from "../types/export";

// 学习记录导出函数 - 使用类型定义
export const exportStudiesToExcel = async (
  studies: StudyExportData[],
  config: ExportConfig = {}
): Promise<ExportResult> => {
  const startTime = Date.now();

  const {
    filename = `学习记录_${new Date().toISOString().split("T")[0]}`,
    format = "xlsx",
    autoWidth = true,
    includeHeader = true,
  } = config;

  try {
    // 准备导出数据 - 使用类型安全的映射
    const exportData = studies.map((study: StudyExportData) => ({
      ID: study.id,
      学习内容: study.content || "",
      学习类型: study.type || "",
      应用场景: study.applicationScenario || "",
      面试频率: study.interviewFrequency
        ? `${study.interviewFrequency}次/周`
        : "未设置",
      备注: study.remark || "无",
      创建时间: study.createdAt
        ? new Date(study.createdAt).toLocaleString("zh-CN")
        : "",
      更新时间: study.updatedAt
        ? new Date(study.updatedAt).toLocaleString("zh-CN")
        : "",
      用户ID: study.userId || "",
    }));

    // 创建工作簿和工作表
    const worksheet = XLSX.utils.json_to_sheet(exportData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "学习记录");

    // 设置列宽
    if (autoWidth) {
      const colWidths = [
        { wch: 8 }, // ID
        { wch: 40 }, // 学习内容
        { wch: 12 }, // 学习类型
        { wch: 20 }, // 应用场景
        { wch: 12 }, // 面试频率
        { wch: 20 }, // 备注
        { wch: 18 }, // 创建时间
        { wch: 18 }, // 更新时间
        { wch: 10 }, // 用户ID
      ];
      worksheet["!cols"] = colWidths;
    }

    // 生成文件
    const excelBuffer = XLSX.write(workbook, {
      bookType: format,
      type: "array",
      bookSST: false,
    });

    const blob = new Blob([excelBuffer], {
      type:
        format === "csv"
          ? "text/csv;charset=utf-8"
          : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });

    // 下载文件
    saveAs(blob, `${filename}.${format}`);

    const duration = Date.now() - startTime;

    return {
      success: true,
      message: "导出成功",
      filename: `${filename}.${format}`,
      count: studies.length,
      duration,
    };
  } catch (error) {
    console.error("导出失败:", error);

    return {
      success: false,
      message: error instanceof Error ? error.message : "导出失败",
      filename: "",
      count: 0,
      duration: Date.now() - startTime,
    };
  }
};

// 带样式的导出函数 - 精美版
export const exportStudiesWithStyle = async (
  studies: StudyExportData[],
  config: ExportConfig = {}
): Promise<ExportResult> => {
  const startTime = Date.now();

  const {
    filename = `学习记录_精美版_${new Date().toISOString().split("T")[0]}`,
    format = "xlsx",
  } = config;

  try {
    // 创建带标题的工作簿
    const workbook = XLSX.utils.book_new();
    
    // 1. 创建标题行
    const titleData = [
      ["学习记录导出报表"],
      [`导出时间: ${new Date().toLocaleString("zh-CN")}`],
      [`总记录数: ${studies.length}`],
      [], // 空行
      ["ID", "学习内容", "学习类型", "应用场景", "面试频率", "备注", "创建时间", "更新时间", "用户ID"]
    ];
    
    // 2. 添加数据行
    const dataRows = studies.map((study: StudyExportData) => [
      study.id,
      study.content || "",
      study.type || "",
      study.applicationScenario || "",
      study.interviewFrequency ? `${study.interviewFrequency}次/周` : "未设置",
      study.remark || "无",
      study.createdAt ? new Date(study.createdAt).toLocaleString("zh-CN") : "",
      study.updatedAt ? new Date(study.updatedAt).toLocaleString("zh-CN") : "",
      study.userId || ""
    ]);
    
    // 合并标题和数据
    const worksheetData = [...titleData, ...dataRows];
    
    // 创建工作表
    const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
    XLSX.utils.book_append_sheet(workbook, worksheet, "学习记录");
    
    // 设置列宽
    const colWidths = [
      { wch: 8 },   // ID
      { wch: 40 },  // 学习内容
      { wch: 12 },  // 学习类型
      { wch: 20 },  // 应用场景
      { wch: 12 },  // 面试频率
      { wch: 20 },  // 备注
      { wch: 18 },  // 创建时间
      { wch: 18 },  // 更新时间
      { wch: 10 }   // 用户ID
    ];
    worksheet["!cols"] = colWidths;
    
    // 合并标题单元格
    worksheet["!merges"] = [
      { s: { r: 0, c: 0 }, e: { r: 0, c: 8 } }, // 第一行标题
      { s: { r: 1, c: 0 }, e: { r: 1, c: 8 } }, // 第二行导出时间
      { s: { r: 2, c: 0 }, e: { r: 2, c: 8 } }  // 第三行记录数
    ];

    // 生成文件
    const excelBuffer = XLSX.write(workbook, {
      bookType: format,
      type: "array",
      bookSST: false,
    });

    const blob = new Blob([excelBuffer], {
      type:
        format === "csv"
          ? "text/csv;charset=utf-8"
          : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });

    // 下载文件
    saveAs(blob, `${filename}.${format}`);

    const duration = Date.now() - startTime;

    return {
      success: true,
      message: "导出成功",
      filename: `${filename}.${format}`,
      count: studies.length,
      duration,
    };
  } catch (error) {
    console.error("带样式导出失败:", error);

    return {
      success: false,
      message: error instanceof Error ? error.message : "带样式导出失败",
      filename: "",
      count: 0,
      duration: Date.now() - startTime,
    };
  }
};

// ==================== 新增：图片中缺失的三个方法 ====================

/**
 * 简洁版Excel导出 - 对应图片中的 exportAsExcel
 */
export const exportAsExcel = async (studies: StudyExportData[], config: Omit<ExportConfig, 'format'> = {}): Promise<ExportResult> => {
  return exportStudiesToExcel(studies, { ...config, format: 'xlsx' });
};

/**
 * 精美版Excel导出 - 对应图片中的 exportWithBeautifulStyle
 */
export const exportWithBeautifulStyle = async (studies: StudyExportData[], config: Omit<ExportConfig, 'format'> = {}): Promise<ExportResult> => {
  return exportStudiesWithStyle(studies, { ...config, format: 'xlsx' });
};

/**
 * CSV导出 - 对应图片中的 exportAsCSV
 */
export const exportAsCSV = async (studies: StudyExportData[], config: Omit<ExportConfig, 'format'> = {}): Promise<ExportResult> => {
  return exportStudiesToExcel(studies, { ...config, format: 'csv' });
};

// ==================== 原有其他函数保持不变 ====================

// 进度跟踪函数
export const createExportProgressTracker = (total: number) => {
  const progress: ExportProgress = {
    current: 0,
    total,
    status: "processing",
    message: "准备开始导出",
  };

  const updateProgress = (current: number, message?: string) => {
    progress.current = current;
    if (message) progress.message = message;

    // 可以在这里添加进度回调或事件发射
    console.log(`导出进度: ${current}/${total} - ${progress.message}`);

    if (current >= total) {
      progress.status = "success";
      progress.message = "导出完成";
    }
  };

  const setError = (message: string) => {
    progress.status = "error";
    progress.message = message;
  };

  return {
    progress,
    updateProgress,
    setError,
  };
};

// 导出筛选后的数据
export const exportFilteredStudies = async (
  studies: StudyExportData[],
  filters: any,
  config: ExportConfig = {}
): Promise<ExportResult> => {
  try {
    // 应用筛选条件
    let filteredData = [...studies];
    
    if (filters.startDate) {
      const start = new Date(filters.startDate);
      filteredData = filteredData.filter(study => 
        new Date(study.createdAt) >= start
      );
    }
    
    if (filters.endDate) {
      const end = new Date(filters.endDate);
      end.setHours(23, 59, 59, 999); // 包含当天
      filteredData = filteredData.filter(study => 
        new Date(study.createdAt) <= end
      );
    }
    
    if (filters.type && filters.type !== "all") {
      filteredData = filteredData.filter(study => 
        study.type === filters.type
      );
    }
    
    if (filters.keyword) {
      const keyword = filters.keyword.toLowerCase();
      filteredData = filteredData.filter(study => 
        study.content.toLowerCase().includes(keyword) ||
        study.applicationScenario.toLowerCase().includes(keyword) ||
        (study.remark && study.remark.toLowerCase().includes(keyword))
      );
    }
    
    // 使用带样式的导出
    return await exportStudiesWithStyle(filteredData, {
      ...config,
      filename: `筛选后的学习记录_${new Date().toISOString().split("T")[0]}`
    });
    
  } catch (error) {
    console.error("筛选导出失败:", error);
    
    return {
      success: false,
      message: error instanceof Error ? error.message : "筛选导出失败",
      filename: "",
      count: 0,
      duration: 0,
    };
  }
};

// 批量导出函数
export const batchExportStudies = async (
  studies: StudyExportData[],
  batchSize: number = 1000,
  config: ExportConfig = {}
): Promise<ExportResult[]> => {
  const results: ExportResult[] = [];
  const totalBatches = Math.ceil(studies.length / batchSize);
  
  const progressTracker = createExportProgressTracker(totalBatches);
  
  try {
    for (let i = 0; i < totalBatches; i++) {
      const start = i * batchSize;
      const end = start + batchSize;
      const batch = studies.slice(start, end);
      
      progressTracker.updateProgress(i + 1, `正在导出第 ${i + 1}/${totalBatches} 批数据`);
      
      const result = await exportStudiesWithStyle(batch, {
        ...config,
        filename: `学习记录_批次${i + 1}_${new Date().toISOString().split("T")[0]}`
      });
      
      results.push(result);
      
      // 添加延迟，避免过快导出导致浏览器卡顿
      if (i < totalBatches - 1) {
        await new Promise(resolve => setTimeout(resolve, 500));
      }
    }
    
    progressTracker.updateProgress(totalBatches, "批量导出完成");
    return results;
    
  } catch (error) {
    progressTracker.setError("批量导出失败");
    throw error;
  }
};